<?php
session_start();
require_once "../basicInfo/user.php";
?>
<?php include "../../layout/header.php"; ?>

<style type="text/css"><!--

#labels
{
   text-align: right;
   width : 115px;
   display: inline;
   float : left;
   clear : left;
}
em.asterik
{
    color: red;
}

 #buttons
 {
    background-color:#DEB887;
    color: white;
    margin-left: 50px;
 }
--></style>
<?php
function CheckForm()
    {
        $message = NULL;
        $counter = 0;
        $maxlength = 35;
        if(empty ($_POST['firstName']))
        {
            $message[$counter] = "Please enter the FirstName";
            ++$counter;
        }
        elseif((strlen($_POST['firstName'])) > $maxlength )
        {
            $message[$counter] = "FirstName should not be greater than 35 characters";
            ++$counter;
        }
        if(empty ($_POST['lastName']))
        {
            $message[$counter] = "Please enter the LastName";
            ++$counter;
        }
        elseif((strlen($_POST['lastName'])) > $maxlength )
        {
            $message[$counter] = "LastName should not be greater than 35 characters";
            ++$counter;
        }
        if(empty ($_POST['emailAddress']))
        {
            $message[$counter] = "Please enter the EmailAddress";
            ++$counter;
        }
        elseif((strlen($_POST['emailAddress'])) > $maxlength )
        {
            $message[$counter] = "EmailAddress should not be greater than 35 characters";
            ++$counter;
        }
        elseif(check_email_address($_POST['emailAddress']) == false )
        {
            $message[$counter] = "Please enter correct emailAddress";
            ++$counter;
        }

        return $message;
    }
    function CheckDateFormat($date)
    {
        $result = 0;

        if (!ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})$",$date, $parts))
        {
            // Check the format
            $result = 1;
            //$errorString = "The date of birth is not a valid date in the format MM/DD/YYYY";
        }
        elseif (!checkdate($parts[1],$parts[2],$parts[3]))
        {
            $result = 2;
            //$errorString = "The date of birth is invalid. Please check that the month is between 1 and 12, and the day is valid for that month.";
        }
        return $result ;
    }
  /*
    function check_email_address($email)
    {
        // First, we check that there's one @ symbol, and that the lengths are right
        if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
        {
            // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
            return false;
        }
        // Split it into sections to make life easier
        $email_array = explode("@", $email);
        $local_array = explode(".", $email_array[0]);
        for ($i = 0; $i < sizeof($local_array); $i++)
        {
            if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
           {
                return false;
           }
        }
        if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
        { // Check if domain is IP. If not, it should be valid domain name

            $domain_array = explode(".", $email_array[1]);
            if (sizeof($domain_array) < 2)
            {
                return false; // Not enough parts to domain
            }
            for ($i = 0; $i < sizeof($domain_array); $i++)
            {
                if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
                {
                    return false;
                }
            }
        }
  return true;
}*/

function check_email_address($email)
 {
    $flag = true;
    // check e-mail address
    // display success or failure message
    if (!preg_match("/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/", $email))
    {
        $flag = false;
    }
   return $flag;
 }
?>


<?php
    //set the current page in the seesion
    $_SESSION['currentPage'] = 'editProfile';
    //declare the variables to be used
    $user = NULL;
    $firstName = NULL;
    $lastName = NULL;
    $emailAddress = NULL;
    $bday = NULL;
    //now retrive the values from the session object
    $serializedUser = $_SESSION['userinfo'];
    $unserializedUser = unserialize($serializedUser);
    $user = $unserializedUser->getUserName();
    $firstName = $unserializedUser->getFirstName();
    $lastName = $unserializedUser->getLastName();
    $emailAddress = $unserializedUser->getEmail();
    $bday = $unserializedUser->getBday();
    $level = $unserializedUser->getLevel();
    $exp = $unserializedUser->getExp();
    $gold = $unserializedUser->getGold();
    $role = $unserializedUser->getRole();
    $isbanned = $unserializedUser->getIsBanned();
    $deaths = $unserializedUser->getDeaths();
    $bug = $unserializedUser->getBugkills();
    $qcreated =$unserializedUser->getQCreated();
    $currentPassword = $unserializedUser->getPassword();
    $imagePath = $unserializedUser->getAvatar();

    $messageArr = NULL;
    //$user is extracted and values of firstname, lastname , emailaddress and current password is retrieved from db
    if(isset($_POST['submit']))
    {

       $firstName = $_POST['firstName'];
       $lastName = $_POST['lastName'];
       $emailAddress = $_POST['emailAddress'];
       $bday = 0;
       $messageArr = CheckForm();
       // update query
       if(!(isset($messageArr)))
       {
           //that means no error then update the db with the values obtained from post method and redirect to the profile page
           UserController::update_user($firstName,$lastName,$user,$emailAddress,$bday);

           //now update the session object
          $userObj = UserController::get_user($user,$firstName, $lastName, $emailAddress, $bday , $level, $exp,
            $gold,$role,$isbanned,$deaths,$bug,$qcreated,$currentPassword, $imagePath );
          $serializedObj = serialize($userObj);
          $_SESSION['userinfo'] = $serializedObj;

          //now redirect to profile page
          header('Location: profile.php' );


       }else{
       	  echo("Hello");
       }
       //on successful execution redirect it to the profile page
       //update the session object
    }


?>

<?php include "../../layout/navleft.php"; ?>
<div id="content_small">
	<div class="container_brown">
		<div class="container_brown_title">Profile</div>
		<div class="profile_div">
		    <form action="editProfile.php" method="Post">
			    <div id="profile_heading">WelCome <?php print $user; ?></div>
			    <br/><br/>
			    <?php if(isset($messageArr))
			    {
			        foreach( $messageArr as $key => $value){
			    ?>
			    <div class="error_text"><em class="asterik">* </em><?php print $value; ?></div>
			    <?php    }
			     } ?>
			    <!--<div class="profile_text">-->
			        <table class="profile_text">
			            <tr><td width="30%"><em class="asterik">* </em>First Name :</td><td><input  type="text" name="firstName" size="20" value=<?php print $firstName; ?>></input></td></tr>
			        	<tr><td><em class="asterik">* </em>Last Name : </td><td><input type="text" name="lastName" size="20" value=<?php print $lastName; ?>></input></td></tr>
			        	<tr><td><em class="asterik">* </em>Email Address :</td><td><input type="text" name="emailAddress" size="20" value=<?php print $emailAddress; ?>></input></td></tr>
			        </table>
			    <!--</div>-->
			    
			    <br><br>
			    <input id="buttons" type="submit" name="submit" value="Update"/>
			    <input id="buttons" type="button" value="Cancel" onclick="window.location = 'editProfile.php'"/>
		    </form>
    	</div>
	</div>
</div>
<?php include "../../layout/navright.php"; ?>
<?php include "../../layout/footer.php"; ?>